import { useEffect, useRef, useState } from "react";
import {
  Card,
  Modal,
  Form,
  Input,
  Select,
  Button,
  Space,
  Row,
  Col,
  Tag,
  Typography,
  Tooltip,
  message,
} from "antd";
import {
  PlayCircleOutlined,
  UploadOutlined,
  DownloadOutlined
} from "@ant-design/icons";

const { Paragraph } = Typography;
const proxyTypes = ["tcp", "udp", "http", "https", "stcp", "xtcp", "sudp"];

const ProxyConfig = ({ proxyList, setProxyList }) => {
  const [modalVisible, setModalVisible] = useState(false);
  const [form] = Form.useForm();
  const [isEditing, setIsEditing] = useState(false);
  const [editingIndex, setEditingIndex] = useState(null);
  const [editingName, setEditingName] = useState(null);
  const [currentType, setCurrentType] = useState("tcp");
  const [frpConfig, setFrpConfig] = useState(null);
  const fileInputRef = useRef(null);

  useEffect(() => {
    refreshList()
  }, [])  

  useEffect(() => {
    setFrpConfig(JSON.parse(localStorage.getItem('frp-global-config') || '{}'))
  }, [])

  /**刷新列表 */
  const refreshList = () => {
    fetch(`http://localhost:3001/api/proxies?frp_path=${encodeURIComponent(getFrpPath())}`)
      .then(res => res.json())
      .then(setProxyList)
  }

  const getFrpPath = () => {
    const config = JSON.parse(localStorage.getItem('frp-global-config') || '{}')
    return config.frp_path || 'C:/frp' // 默认路径
  }
  const getFrpServer = () => {
    const config = JSON.parse(localStorage.getItem('frp-global-config') || '{}')
    return config.server_addr || '127.0.0.1' // 默认路径
  }
  /**添加代理 */
  const openAddModal = () => {
    form.resetFields();
    setIsEditing(false);
    setCurrentType("tcp");
    setModalVisible(true);
  };

  const handleEdit = (proxy, index) => {
    form.setFieldsValue(proxy);
    setCurrentType(proxy.type);
    setEditingIndex(index);
    setEditingName(proxy.name)
    setIsEditing(true);
    setModalVisible(true);
  };

  const handleSubmit = () => {
    form.validateFields().then((values) => {
      // 默认启用新配置
      if (values.enabled === undefined) values.enabled = true;

      const newList = [...proxyList];
      if (isEditing && editingIndex !== null) {
        newList[editingIndex] = values;
      } else {
        newList.push(values);
      }
      if(isEditing) {
        fetch(`http://localhost:3001/api/proxies/?oldName=${editingName}&frp_path=${encodeURIComponent(getFrpPath())}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(values),
        }).then(async res => {
          const data = await res.json()
          if (res.ok) {
            message.success(data.message)
            setModalVisible(false);
            refreshList()
          }else {
            message.error(data.message)
          }
        })
      }else {
        fetch(`http://localhost:3001/api/proxies?frp_path=${encodeURIComponent(getFrpPath())}`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(values),
        }).then(async res => {
          const data = await res.json()
          if (res.ok) {
            message.success(data.message)
            setProxyList(newList);
            setModalVisible(false);
            refreshList()
          }else {
            message.error(data.message)
          }
        })
      }
      
    });
  };

  const triggerImport = () => {
    if (fileInputRef.current) fileInputRef.current.click();
  };

  /**导入配置 */
  const handleImport = (event) => {
    const file = event.target.files[0];
    if (!file) return;
    const reader = new FileReader();
    reader.onload = (e) => {
      const text = e.target.result;
      try {
        const config = JSON.parse(text);
        setProxyList(config.proxies);
        message.success('配置导入成功');
      } catch (err) {
        message.error('配置解析失败');
      }
    };
    reader.readAsText(file);
  }
  /**导出配置 */
  const handleExport = async () => {
    const config = JSON.parse(localStorage.getItem('frp-global-config') || '{}')
    const frpPath = config.frp_path
  
    if (!frpPath) {
      message.warning('请先保存或填写全局配置')
      return
    }
  
    try {
      const res = await fetch(`http://localhost:3001/api/export?frp_path=${encodeURIComponent(frpPath)}`)
      if (!res.ok) throw new Error('导出失败')
  
      const blob = await res.blob()
      const url = window.URL.createObjectURL(blob)
  
      const a = document.createElement('a')
      a.href = url
      a.download = 'frpc.toml'
      document.body.appendChild(a)
      a.click()
      a.remove()
      window.URL.revokeObjectURL(url)
  
      message.success('配置文件已下载')
    } catch (err) {
      message.error('导出失败：' + err.message)
    }
  }
  

  /**删除代理 */
  const handleDelete = (e,name,index) => {
    e.stopPropagation();
    /**确认删除吗 */
    Modal.confirm({
      title: '确认删除吗',
      content: `确定删除代理 ${name} 吗？`,
      okText: '删除',
      okType: 'danger',
      onOk: () => {
        const newList = [...proxyList];
        fetch(`http://localhost:3001/api/proxies/${name}?frp_path=${encodeURIComponent(getFrpPath())}`, {
          method: 'DELETE',
          headers: { 'Content-Type': 'application/json' },
        }).then(async res => {
          const data = await res.json()
          if (res.ok) {
            newList.splice(index, 1);
            setProxyList(newList);
            message.success(data.message)
            refreshList()
          }else {
            message.error(data.message)
          }
        })
      },
      cancelText: '取消',
    })
  }

  const toggleEnable = (index) => {
    const newList = [...proxyList];
    newList[index].enabled = !newList[index].enabled;
    setProxyList(newList);
  };

  const getMappingUrl = (proxy) => {
    if (proxy.custom_domains) {
      return `http://${proxy.custom_domains}`;
    }
    if (proxy.type === "tcp" || proxy.type === "udp") {
      return proxy.remote_port ? `http://${getFrpServer()}:${proxy.remote_port}` : "";
    }
    return "";
  };

  const renderExtraFields = (type) => {
    const commonFields = (
      <Form.Item
        label="内网地址 (local_ip)"
        name="local_ip"
        rules={[{ required: true }]}
      >
        <Input placeholder="如：127.0.0.1" />
      </Form.Item>
    );

    switch (type) {
      case "http":
      case "https":
        return (
          <>
            {commonFields}
            <Form.Item
              label="本地端口 (local_port)"
              name="local_port"
              rules={[{ required: true }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="自定义域名 (custom_domains)"
              name="custom_domains"
              rules={[{ required: true }]}
            >
              <Input placeholder="如：example.com" />
            </Form.Item>
          </>
        );
      case "stcp":
      case "xtcp":
        return (
          <>
            {commonFields}
            <Form.Item
              label="秘钥 (sk)"
              name="sk"
              rules={[{ required: true }]}
            >
              <Input placeholder="用于 STCP/XTCP 加密通信" />
            </Form.Item>
          </>
        );
      default:
        return (
          <>
            {commonFields}
            <Form.Item
              label="本地端口 (local_port)"
              name="local_port"
              rules={[{ required: true }]}
            >
              <Input />
            </Form.Item>
            <Form.Item label="远程端口 (remote_port)" name="remote_port">
              <Input placeholder="可留空自动分配" />
            </Form.Item>
          </>
        );
    }
  };

  return (
    <Space direction="vertical" style={{ width: "100%" }} size="large">
      <Space>
        <Button type="primary" onClick={openAddModal}>
          添加代理配置
        </Button>
        <Button icon={<DownloadOutlined />} onClick={handleExport}>
          导出配置
        </Button>
      </Space>
      {/* <Button icon={<UploadOutlined />}  onClick={triggerImport}>
        导入配置
      </Button>
      <input
        ref={fileInputRef}
        type="file"
        accept="application/json"
        onChange={handleImport}
        style={{ display: "none" }}
      /> */}
      

      <Modal
        title={isEditing ? "编辑代理配置" : "添加代理配置"}
        open={modalVisible}
        onCancel={() => setModalVisible(false)}
        onOk={handleSubmit}
        okText={isEditing ? "保存修改" : "添加"}
      >
        <Form
          layout="vertical"
          form={form}
          initialValues={{ type: "tcp", local_ip: "127.0.0.1", enabled: true }}
        >
          <Form.Item
            label="代理名称 (name)"
            name="name"
            rules={[{ required: true }]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="代理类型 (type)"
            name="type"
            rules={[{ required: true }]}
          >
            <Select onChange={(val) => setCurrentType(val)}>
              {proxyTypes.map((type) => (
                <Select.Option key={type} value={type}>
                  {type.toUpperCase()}
                </Select.Option>
              ))}
            </Select>
          </Form.Item>
          {renderExtraFields(currentType)}
          <Form.Item
            name="enabled"
            valuePropName="checked"
            style={{ marginTop: 12 }}
          >
            <Tooltip title="是否启用该代理">
              <Button
                type="default"
                onClick={() => {
                  const cur = form.getFieldValue("enabled");
                  form.setFieldsValue({ enabled: !cur });
                }}
              >
                {form.getFieldValue("enabled") ? "启用中" : "已禁用"}
              </Button>
            </Tooltip>
          </Form.Item>
        </Form>
      </Modal>

      <Row gutter={[16, 16]}>
        {proxyList.map((proxy, index) => {
          const mappingUrl = getMappingUrl(proxy);
          return (
            <Col span={8} key={index}>
              <Card
                size="small"
                hoverable
                style={{
                  borderRadius: 12,
                  boxShadow: "0 2px 8px rgba(0,0,0,0.08)",
                  transition: "0.3s",
                  opacity: proxy.enabled === false ? 0.5 : 1,
                  cursor: "pointer",
                }}
                title={
                  <div
                    style={{
                      display: "flex",
                      flexWrap: "wrap",
                      gap: 8,
                      alignItems: "center",
                    }}
                  >
                    <strong>{proxy.name}</strong>
                    <Tag color="blue" style={{ lineHeight: "20px" }}>
                      {proxy.type.toUpperCase()}
                    </Tag>
                    {proxy.enabled === false && (
                      <Tag color="red" style={{ lineHeight: "20px" }}>
                        已禁用
                      </Tag>
                    )}
                  </div>
                }
                onClick={() => handleEdit(proxy, index)}
                extra={
                  <Button
                    danger
                    size="small"
                    onClick={(e) => {
                      handleDelete(e, proxy.name,index)
                    }}
                  >
                    删除
                  </Button>
                }
              >
                <p style={{ marginBottom: 4 }}>
                  内网地址：
                  <Tag>
                    {proxy.local_ip}:{proxy.localPort || proxy.local_port || "-"}
                  </Tag>
                </p>
                <p style={{ marginBottom: 0 }}>
                  映射地址：
                  {mappingUrl ? (
                    <Paragraph copyable={{ text: mappingUrl }} style={{ display: "inline-block", margin: 0 }}>
                      <a href={mappingUrl} target="_blank" rel="noopener noreferrer">
                        {mappingUrl}
                      </a>
                    </Paragraph>
                  ) : (
                    <Tag color="default">自动分配</Tag>
                  )}
                </p>
                {/* <Button
                  type={proxy.enabled ? "default" : "primary"}
                  onClick={(e) => {
                    e.stopPropagation();
                    toggleEnable(index);
                  }}
                  style={{ marginTop: 8 }}
                  block
                >
                  {proxy.enabled ? (
                    <>
                      <PauseCircleOutlined /> 禁用代理
                    </>
                  ) : (
                    <>
                      <PlayCircleOutlined /> 启用代理
                    </>
                  )}
                </Button> */}
              </Card>
            </Col>
          );
        })}
      </Row>
    </Space>
  );
};

export default ProxyConfig;
